import React from 'react'
// ===================================================================== Temp
import Table from '#cpt/temp/Table'
import SubmitForm from '#cpt/temp/SubmitForm'
import Controls from '#cpt/temp/Controls'
import Confirm from '#cpt/temp/Confirm'
// ===================================================================== global declare
const { $fn, $http, $Lazy } = window
// ===================================================================== $Lazy
const message 			= $Lazy.file(()=>import('@antd/message'))
const $cache 			= $Lazy.file(()=>import('#private/cache-api'))
const confirm 			= $Lazy.file(()=>import('@antd/confirm'))
const Printer 			= $Lazy.hook(()=>import('#private/printer'))
const BatchShelves		= $Lazy.state(()=>import('./batch-shelves-modal'))
const SpecBatchModal	= $Lazy.state(()=>import('./spec-batch-modal'))
const ResetNumber		= $Lazy.state(()=>import('./reset-number-modal'))
const SaoImage			= $Lazy.load(()=>import('#tp/sao'))
const width = '33.33%'
// ===================================================================== component
const afterSuffix = <SaoImage size={19} className='ml5' />
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		selectedKeys:[],
		selectedRows:[],
		isThirdHosp: false,	// 是否 启用第三方条码
		isPrinter: 1,	// 是否 打印
		link: 1,
		isKeyEvent: false,	// 键盘快捷键拆分
		// 搜索表单列表
		formData : [
			{ label: '标本号',	afterSuffix,	name: 'spec_code',	itemClassName:'spec_code',	outer:true, width,	autoFocus:false,	
				onValue:({value})=>{if(value){this.submit.spec_code = value}},
				onEnter: (value)=> {this.dataEntry()}
			},
			{ label: '标本架编号',				name: 'sf_number',		width,	disabled: true,	p:' ',	itemClassName:'specimen-putaway', },
			{ label: '岗位组',					name: 'project_name',	width,	disabled: true,	p:' ',	itemClassName:'specimen-putaway', },
			{ label: ' ', 	tag: '打印实验号',  	name: 'is_printer',	value:1,	width,	type: 'checkbox', style: {paddingLeft:10}, 	
				onValue:({value, formData})=>{
					$fn.hideRows(formData,'number', !value)
					this.setState({ formData, isPrinter: value})
				}
			},
			{ label: '打印份数',					name: 'number',	width,	value:1,	type:'number',	 onValue:({value})=>{this.setState({link:parseInt(value)})
			} },
			{ label: ' ', 	tag: '是否启用第三方条码', 	name: 'is_third_hosp', 	width,		type: 'checkbox', 	style: {paddingLeft:10,}, 	
				onValue:({value,formData})=>{
					$fn.hideRows(formData,'third_hosp', !value)
					this.setState({formData, isThirdHosp: Boolean(value)})
				}
			},
			{ label: '第三方医院',	hide:true,	name: 'third_hosp',	type:'select',	width,	loading:true, 	onValue:({value})=>{this.submit.third_hosp = value} },
			{ label: ' ', 	tag: '混检批量上架',	name: 'isMixed',	type: 'checkbox', width,	style: {paddingLeft:10,},  onValue:({value})=>{this.submit.isMixed = Boolean(value)}},
		],
		spec_code:'',
	}
	model = {}
	submit = {}
	componentDidMount(){		
		this.getSelect()
		this.fetch()
		this.submit.isMixed = false
		document.addEventListener("keydown", this.handleKeyDown);
	}
	componentWillUnmount(){
		document.removeEventListener("keydown", this.handleKeyDown)
	}
	
	// 获取下拉数据
	getSelect = () => {
		const { formData } = this.state
		
		$cache.then( async f => {
			// 医院
			$fn.setRow( formData, 'third_hosp', await f.getCache({ api:'hospital' }) )
			
			this.setState({ formData })
		})
	}
	onrowTable = (param) => {
		this.model = {}
		this.query = param ? param : {}
		this.fetch()
	}
	
	// paging
	fetch = () => {
		$fn.fetch.call(this,'shelf/upshelflist')
	}
	// 表单
	cols = [
		{ title: '序号', 			dataIndex: 'sort', 				width:50 },
		{ title: '标本号', 			dataIndex: 'spec_code', 		...$fn.table.spec_code },
		{ title: '标本架编号', 		dataIndex: 'sf_number', 		...$fn.table.exp_num },
		{ title: '岗位组', 			dataIndex: 'project_name', 		width:130 },
		{ title: '自然项目', 		dataIndex: 'kind_name', 		width:200 },
		{ title: '第三方条码', 		dataIndex: 'third_spec_code',  	...$fn.table.spec_code},
		{ title: '实验号', 			dataIndex: 'lb_tpl',  			...$fn.table.exp_num},
	]
	controls = ()=> {
		/* 标本上架增加批量上架 2021-7-28  --马婷 */
		return [
			this.props.isSpec ? Controls.click.call(this, '重置实验号', ()=>{this.resetNumberModal.open()} ) : null,
			Controls.click.call(this, '录入', ()=> {this.dataEntry()}, {code:'F2'} ),
			!this.props.isSpec ? Confirm.call(this, '批量上架', '', {
				onOk:(close)=> {
					close()
					this.batchShelvesModal.open()
				},
				msg:'非IT技术人员禁止操作批量上架'
			} ) : null,
			this.props.isSpec ? Controls.click.call(this, '批量上架', ()=>{ this.specBatchModal.open() } ) : null,
			Controls.click.call(this, '查看全部',()=>{
				this.model = this.query = {}
				this.fetch()
			},{ code:'F3' } ),
		]
	}
	
	// 录入
	dataEntry = ()=> {
		if(this.state.isThirdHosp) {
			this.putawayThird_spec()
		}else {
			this.enterCode()
		}
	}
	
	// 第三方条码上架
	putawayThird_spec = ()=> {
		const { spec_code, third_hosp } = this.submit
		$http.submit(null,'shelf/thirdspecdata',{ param:{ third_spec: spec_code,third_hosp },loading:false}).then(({spec_code})=>{
			this.submit.spec_code = spec_code
			this.enterCode()
		})
	}
	
	// 录入条码
	enterCode = ()=> {
		const { formData } = this.state
		const { spec_code, isMixed } = this.submit
		this.formRef.reset(['spec_code'] )
		$fn.getRow(formData, 'spec_code').autoFocus = true
		this.setState({formData})
		$http.submit(null,'shelf/alertsplit',{ param:{ spec_code, isMixed },loading:false}).then(({ alert_split, alert_lists, old_spec_code, project_num, project_names})=>{
			if(this.props.isSpec) {this.props.getAlertList(alert_lists)}
			if( alert_split=== '1' ){
				this.setState({isKeyEvent: true,spec_code: old_spec_code})
				confirm.then(f=>{
					this.confirm = f({
						msg:`是否直接拆分？此次拆分涉及到${project_num}个岗位【${project_names}】`,
						okText:'是',
						cancelText:'否',
						closable:true,
						onOk:()=> {
							this.splits(old_spec_code)
							this.setState({isKeyEvent:false})
						},
						onCancel:()=> {
							this.noSplits(old_spec_code)
							this.setState({isKeyEvent:false})
						}
					})
				})
				
			}else {
				if(isMixed){
					this.submit.spec_code = old_spec_code
				}
				this.UpperFrameEntry()
			}
		})
	}
	// 拆分
	splits = (old_spec_code)=> {
		$http.submit(null,'shelf/autosplit',{ param:{ old_spec_code },loading:false}).then(({project_name,sf_number})=>{
			message.then(f=>f.success(`操作成功`))
			this.fetch()
			this.props.onRefresh()
			this.updateTable()
			this.formRef.setValue({sf_number,project_name})
			this.submit.spec_code = ''
			this.printers(old_spec_code)
		})
		this.confirm.destroy()
		document.querySelector('.spec_code .ant-input.ant-input-borderless').focus()
		
	}
	// 不拆分
	noSplits = (old_spec_code)=> {
		this.submit.spec_code = old_spec_code
		this.UpperFrameEntry()
		this.confirm.destroy()
		document.querySelector('.spec_code .ant-input.ant-input-borderless').focus()
	}
	// 拆分时对是否直接拆分添加快捷键左右键
	handleKeyDown = (e)=> {
		let key = window.event.keyCode || window.event.which;
		if (this.state.isKeyEvent) {
			if (key === 37) {	// 向左键 - 否
			this.noSplits(this.state.spec_code)
			} else if (key === 39) {	// 向右键 - 是
				this.splits(this.state.spec_code)
			}
		}
	}
	// 上架条码
	UpperFrameEntry = ()=> {
		const { spec_code, isMixed} = this.submit
		$http.submit(null,'shelf/getshelf',{ param:{ spec_code },loading:false}).then(({project_name,sf_number})=>{
			this.formRef.setValue({sf_number,project_name})
			if(isMixed){
				$http.submit(null,'shelf/upShelfMixSample',{ param:{ sf_number, project_name, spec_code },loading:false}).then(data=>{
					message.then(f=>f.success(`操作成功`))
					this.updateTable()
					this.fetch()
					this.props.onRefresh()
					this.printers(spec_code)
					this.submit.spec_code = ''
				})
			}else{
				$http.submit(null,'shelf/upshelf',{ param:{ sf_number, project_name, spec_code },loading:false}).then(data=>{
					message.then(f=>f.success(`操作成功`))
					this.updateTable()
					this.fetch()
					this.props.onRefresh()
					this.printers(spec_code)
					this.submit.spec_code = ''
				})
			}
			
		})
	}
	// 上架成功后更新 左下 表格
	updateTable = ()=> {
		const { spec_code} = this.submit
		$http.submit(null,'shelf/splitSpecLists',{ param:{spec_code },loading:false}).then(data=>{
			if(this.props.isSpec) this.props.getAlertList(data)
		})
	}
	
	// 打印
	printers(spec_code) {
		let { link } = this.state
		const { isMixed } = this.submit
		if (this.state.isPrinter) {
		$http.submit(null,'shelf/printshelf	',{ param:{ spec_code, isMixed },loading:false}).then(data=>{
			if(data.length){
				this.printerRef.printer({ code: 50104, data, loading:false,link:+link})
			}
		})
		}
	}

		
	render(){
		return (
			<>
				{/* 搜索 */}
				<div className='pt10'>{ SubmitForm.call(this, { labelWidth:'s6', mb:5 } ) }</div>
				{/* 表格 */}
				{ Table.call(this, {type: -1 }) }
				{/* 重置实验号弹框 */}
				<ResetNumber onRef = { ref => this.resetNumberModal = ref } />
				{/* 打印 */}
				<Printer onRef = { ref => this.printerRef = ref } hasBtn = {false} tips = {true}   />
				{/* 批量上架 */}
				<BatchShelves onRef = { ref => this.batchShelvesModal = ref } onRefresh={()=>{
					this.fetch()
					this.props.onRefresh()
				}} />
				<SpecBatchModal onRef = { ref => this.specBatchModal = ref } onRefresh={()=>{
					this.fetch()
					this.props.onRefresh()
				}} />
			</>
		)
	}
}

export default Index